package pl.lodz.p.browarex.mvc;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import pl.lodz.p.browarex.model.AnalysisType;
import pl.lodz.p.browarex.model.OrderProductInfo;
import pl.lodz.p.browarex.model.User;
import pl.lodz.p.browarex.model.enums.AnalysisTypeEnum;
import pl.lodz.p.browarex.services.interfaces.IAnalysisTypeService;
import pl.lodz.p.browarex.services.interfaces.ICustomerService;
import pl.lodz.p.browarex.services.interfaces.IProductService;
import pl.lodz.p.browarex.services.interfaces.IUserService;

@Controller
public class SearchController {

	@Inject
	IProductService productService;

	@Inject
	IUserService userService;

	@Inject
	IAnalysisTypeService analysisTypeService;

	@Inject
	ICustomerService customerService;

	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public String search(Model model, HttpServletRequest request) {

		String searchString = request.getParameter("searchedProduct");

		model.addAttribute("orderProductInfo", new OrderProductInfo());
		model.addAttribute("foundedProduct",
				productService.findProductByName(searchString));
		model.addAttribute("searchedProduct", searchString);

		User user = userService.getLogged();

		if (user != null) {
			AnalysisType analysisList = analysisTypeService
					.loadByCustomerID(customerService.getByUsername(
							user.getUsername()).getCustomerID());
			if (analysisList != null) {
				for (int i = 0; i < analysisList.getAnalysies().size(); i++) {
					if (AnalysisTypeEnum.REGION_MATCH.equals(analysisList
							.getAnalysies().get(i).getType())
							&& analysisList.getAnalysies().get(i)
									.getProductID() != null) {
						String brandURL = "<a href = \"product?id="
								+ analysisList.getAnalysies().get(i)
										.getProductID()
								+ "\">tutaj" + "</a>";
						model.addAttribute("link", brandURL);
					}
				}
			}
		}

		return "search";
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public String getSearch() {
		return "redirect:index";
	}

}
